<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\admin\model\UserMoneyLog;
use app\admin\model\Wechat;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 提现管理
 *
 */
class Withdrawal extends Backend
{
    /**
     * Withdrawal模型对象
     * @var \app\admin\model\Withdrawal
     */
    protected $model = null;

    protected $quickSearchField = ['id'];

    protected $defaultSortField = 'id,desc';

    protected $withJoinTable = ['user'];

    protected $preExcludeFields = ['createtime', 'updatetime'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Withdrawal;
    }

    public function edit()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if (isset($data['state']) && in_array($data['state'], [1, 2])) {
                    $data['checktime'] = time();
                    if ($data['state'] == 1) {
                        $user = User::where('id', $data['user_id'])->find();
                        $wechat = new Wechat();
                        $res = $wechat->getPayment()->transfer->toBalance([
                            'partner_trade_no' => $data['order_sn'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                            'openid' => $user->routine_openid,
                            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                            'amount' => 1, // 企业付款金额，单位为分
                            'desc' => '提现', // 企业付款操作说明信息。必填
                        ]);
                        if (isset($res['result_code']) && $res['result_code'] == 'FAIL') {
                            throw new ValidateException($res['err_code_des']);
                        }
                    } elseif ($data['state'] == 2) {
                        $moneyLog = new UserMoneyLog;
                        $moneyLog->create([
                            'user_id' => $data['user_id'],
                            'money' => $data['money'],
                            'memo' => '驳回提现',
                        ]);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $row->nickname = User::where('id', $row->user_id)->value('nickname');
        $row['ed'] = 0;
        if ($row['state'] != 0) {
            unset($row['state']);
            $row['ed'] = 1;
        }
        $this->success('', [
            'row' => $row
        ]);
    }

}